package com.ys.peony.ui.activity;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ys.peony.R;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.contract.BasicActivity;
import com.ys.peony.base.contract.CarPledgeContract;
import com.ys.peony.car300.CarDataManager;
import com.ys.peony.car300.CarInfo2Activity;
import com.ys.peony.car300.ItemModel;
import com.ys.peony.car300.ListSelectActivity;
import com.ys.peony.car300.ui.ChoiceCarTypeActivity;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.model.domain.CarAddInfo;
import com.ys.peony.model.domain.CarDetailModel;
import com.ys.peony.model.domain.CarModel;
import com.ys.peony.presenter.CarPledgePresenter;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;
import com.ys.peony.view.YsDialogItemModel;
import com.ys.peony.view.inter.YsDailogClickListener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CarInfoActivity extends BasicActivity<CarPledgeContract.iCarInfoView, CarPledgePresenter> implements CarPledgeContract.iCarInfoView, View.OnClickListener, YsDailogClickListener {

    private static final String PARAM_LOANID = "loanId";

    @BindView(R.id.vin_editor)
    EditText vin_editor;
    @BindView(R.id.guohu_et)
    EditText guohu_et;
    @BindView(R.id.input1)
    TextView input1;
    @BindView(R.id.input2)
    TextView input2;

    @BindView(R.id.car_logo)
    RelativeLayout car_logo;
    @BindView(R.id.car_sort)
    RelativeLayout car_sort;
    @BindView(R.id.car_num)
    RelativeLayout car_num;
    @BindView(R.id.car_color)
    RelativeLayout car_color;
    @BindView(R.id.car_gongkuang)
    RelativeLayout gongkuang;
    @BindView(R.id.car_decorate)
    RelativeLayout car_decorate;
    @BindView(R.id.car_apperance)
    RelativeLayout car_apperance;


    @BindView(R.id.car_num_tv)
    TextView car_num_tv;
    @BindView(R.id.car_logo_tv)
    TextView car_logo_tv;
    @BindView(R.id.car_sort_tv)
    TextView car_sort_tv;
    @BindView(R.id.car_color_tv)
    TextView car_color_tv;
    @BindView(R.id.car_gongkuang_tv)
    TextView car_gongkuang_tv;
    @BindView(R.id.car_decorate_tv)
    TextView car_decorate_tv;
    @BindView(R.id.car_apperance_tv)
    TextView car_apperance_tv;

    @BindView(R.id.next)
    Button next;

    private YsDialogItemModel mDialogItemModel;
    private String loanId;
    private CarModel.ModelInfoBean mCarInfo = null;

    @Override
    protected CarPledgePresenter initPresenter() {
        return new CarPledgePresenter();
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_car_info;
    }

    @Override
    protected void initView() {
        super.initView();
        //清理数据
        initData();
        initWidget();
        initListener();
    }


    private void initData() {
        CarDataManager.getInstance().setCarVinModel(null);
        Bundle bundle = getIntent().getExtras();
        loanId = bundle.getString(PARAM_LOANID);

        if (!TextUtils.isEmpty(loanId)) {
            saveId(loanId);
            presenter.getCarInfoById(loanId);
        } else {
            ToastUtils.showToast("数据请求失败，业务loanId为空");
        }

    }

    private void saveId(String loanId) {
        CarDataManager.getInstance().setLoanId(loanId);
        CarDataManager.getInstance().setUserId(SharePreferencesUtils.getInstance().getUserId());
    }

    private void initWidget() {

        vin_editor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                vin_editor.removeTextChangedListener(this);//解除文字改变事件
                input1.setText(String.valueOf(charSequence.length()));
                int t = 17 - charSequence.length();
                input2.setText(String.valueOf(t));
                car_logo_tv.setText("");
                car_sort_tv.setText("");
                car_num_tv.setText("");
                vin_editor.setText(charSequence.toString().toUpperCase());
                vin_editor.setSelection(charSequence.toString().length());//重新设置光标位置
                vin_editor.addTextChangedListener(this);//重新绑
                /*if (presenter.isValidInput(input) && input.equals("LFV3A24F3A3026881")) {
                    LoadingProgressUtils.showProgressDialog(getBaseContext());
                    presenter.getCarByVin(input);
                }*/
                //LFV3A24F3A3026881
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        vin_editor.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String input = vin_editor.getText().toString().trim();
                    if (presenter.isValidInput(input)) {
                        hideInput();
                        LoadingProgressUtils.showProgressDialog(getBaseContext());
                        presenter.getCarByVin(input);
                    }
                }
                return false;
            }
        });
        mDialogItemModel = new YsDialogItemModel(this, this);
    }

    private void initListener() {
        car_sort.setOnClickListener(this);
        car_logo.setOnClickListener(this);
        car_color.setOnClickListener(this);
        car_decorate.setOnClickListener(this);
        car_apperance.setOnClickListener(this);
        gongkuang.setOnClickListener(this);
        car_num.setOnClickListener(this);
        next.setOnClickListener(this);
        vin_editor.setOnClickListener(this);

    }

    private void updatePart1View(CarModel carModel) {
        if (carModel != null) {
            List<CarModel.ModelInfoBean> modelInfoBeanList = carModel.getModelInfo();
            if (modelInfoBeanList == null || modelInfoBeanList.size() == 0) {
                return;
            }
            CarDataManager.getInstance().getmCarAddInfo().setVehicle_id(vin_editor.getText().toString().trim());
            if (modelInfoBeanList.size() == 1) {
                CarModel.ModelInfoBean modelInfoBean = modelInfoBeanList.get(0);
                mCarInfo = modelInfoBean;
                saveCarParam();
                CarAddInfo carAddInfo = CarDataManager.getInstance().getmCarAddInfo();
                carAddInfo.setModel_id(String.valueOf(mCarInfo.getModel_id()));
                carAddInfo.setModel_id_desr(mCarInfo.getModel_name());
                car_num_tv.setText(modelInfoBean.getModel_name());
                car_logo_tv.setText(modelInfoBean.getBrand_name());
                car_sort_tv.setText(modelInfoBean.getSeries_name());
            } else {
                jumpCarTypeSelect();
            }
        }

    }

    @Override
    public void onResult(Object o) {
        LoadingProgressUtils.closeDialog();
        if (o instanceof CarModel) {
            CarModel carModel = (CarModel) o;
            updatePart1View(carModel);
        }
    }

    private void jumpCarTypeSelect() {
        if (CarDataManager.getInstance().getCarVinModel().getModelInfo().size() > 1) {
            skipToTargetPage(ChoiceCarTypeActivity.class, null, SwipeDirect.DIRECT_LEFT, true);
        } else {
            ToastUtils.showToast("无其他车型选择");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ListSelectActivity.RESULT_OK) {
            int position = data.getIntExtra(ChoiceCarTypeActivity.RESULT_POSITION, YSConstant.INVALID);
            CarModel carModel = CarDataManager.getInstance().getCarVinModel();
            if (carModel == null || position == YSConstant.INVALID) {
                return;
            }

            CarModel.ModelInfoBean modelInfoBean = carModel.getModelInfo().get(position);
            if (modelInfoBean != null && !TextUtils.isEmpty(modelInfoBean.getModel_name())) {
                mCarInfo = modelInfoBean;
                saveCarParam();
                car_num_tv.setText(modelInfoBean.getModel_name());
                car_logo_tv.setText(modelInfoBean.getBrand_name());
                car_sort_tv.setText(modelInfoBean.getSeries_name());
            }
            CarAddInfo carAddInfo = CarDataManager.getInstance().getmCarAddInfo();
            carAddInfo.setModel_id(String.valueOf(modelInfoBean.getModel_id()));
            carAddInfo.setModel_id_desr(modelInfoBean.getModel_name());

        }
    }

    private void saveCarParam() {
        if (mCarInfo != null && mCarInfo.getDiff_params() != null) {
            CarModel.ModelInfoBean.DiffParamsBean.StandardGroupBean standardGroupBean = mCarInfo.getDiff_params().getStandard_group();
            if (standardGroupBean != null) {
                try {
                    Field[] fields = standardGroupBean.getClass().getDeclaredFields();
                    List<String> list = new ArrayList<>();
                    for (int i = 0; i < fields.length - 2; i++) {
                        String value = String.valueOf(fields[i].get(standardGroupBean));
                        if (ChoiceCarTypeActivity.CONFIG_TYPE.equals(value)) {
                            list.add(fields[i].getName());
                        }
                    }
                    if (list.size() > 0) {
                        CarAddInfo.CarTypeParam carTypeParam = new CarAddInfo.CarTypeParam();
                        carTypeParam.setOne(list);
                        CarDataManager.getInstance().getmCarAddInfo().setCarTypeParam(carTypeParam);
                    } else {
                        CarDataManager.getInstance().getmCarAddInfo().setCarTypeParam(null);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        List<ItemModel> itemModels;

        CarDetailModel carDetailModel = CarDataManager.getInstance().getCarDetailModel();
        if (carDetailModel == null && view.getId() != R.id.vin_editor) {
            ToastUtils.showToast("数据正在请求中");
            return;
        }
        switch (view.getId()) {
            case R.id.car_gongkuang:
                itemModels = presenter.getItemModel(carDetailModel.getVehicleCarworkstateList(), view.getId());
                if (itemModels != null && itemModels.size() > 0) {
                    mDialogItemModel.setItemModels(itemModels, YSConstant.POP_TYPE_GONGKUANG);
                }
                break;
            case R.id.car_color:
                itemModels = presenter.getItemModel(carDetailModel.getVehicleCarcolorList(), view.getId());
                if (itemModels != null && itemModels.size() > 0) {
                    mDialogItemModel.setItemModels(itemModels, YSConstant.POP_TYPE_COLOR);
                }
                break;
            case R.id.car_decorate:
                itemModels = presenter.getItemModel(carDetailModel.getVehicleCarinteriorList(), view.getId());
                if (itemModels != null && itemModels.size() > 0) {
                    mDialogItemModel.setItemModels(itemModels, YSConstant.POP_TYPE_DECORATE);
                }
                break;
            case R.id.car_apperance:
                itemModels = presenter.getItemModel(carDetailModel.getVehicleCarsurfaceList(), view.getId());
                if (itemModels != null && itemModels.size() > 0) {
                    mDialogItemModel.setItemModels(itemModels, YSConstant.POP_TYPE_APPERANCE);
                }
                break;
            case R.id.car_num:
                if (TextUtils.isEmpty(car_sort_tv.getText().toString().trim()) || TextUtils.isEmpty(car_logo_tv.getText().toString().trim())) {
                    ToastUtils.showToast("请先输入vin码");
                    return;
                }
                jumpCarTypeSelect();
                break;
            case R.id.next:
                if (checkCarInfo()) {
                    saveCarInfo();
                    skipToTargetPage(CarInfo2Activity.class, null);
                } else {
                    ToastUtils.showToast("请完善必要信息");
                }
                break;
            case R.id.car_logo:
                ToastUtils.showToast("车辆品牌不可更改");
                break;
            case R.id.car_sort:
                ToastUtils.showToast("车系不可更改");
                break;
            case R.id.vin_editor:
                vin_editor.setCursorVisible(true);
                break;
        }

    }

    private Boolean checkCarInfo() {
        if (TextUtils.isEmpty(car_num_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_logo_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_sort_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_color_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_gongkuang_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_decorate_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_apperance_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(guohu_et.getText().toString().trim())) {
            return false;
        }
        return true;
    }

    private void saveCarInfo() {
        CarAddInfo carAddInfo = CarDataManager.getInstance().getmCarAddInfo();
        if (mCarInfo != null) {
            carAddInfo.setVehicle_type(car_num_tv.getText().toString().trim());
            carAddInfo.setBrand_name(car_logo_tv.getText().toString().trim());
            carAddInfo.setBrand_id(String.valueOf(mCarInfo.getBrand_id()));
            carAddInfo.setSeries_id(String.valueOf(mCarInfo.getSeries_id()));
            carAddInfo.setSeries_id_desr(mCarInfo.getSeries_name());
            carAddInfo.setTransfer_times(guohu_et.getText().toString().trim());
            carAddInfo.setLoanID(loanId);
        }
    }


    @Override
    public void clickDialogItemModel(int type, ItemModel itemModel) {
        if (itemModel == null) {
            return;
        }
        switch (type) {
            case YSConstant.POP_TYPE_GONGKUANG:
                car_gongkuang_tv.setText(itemModel.getText());
                CarDataManager.getInstance().getmCarAddInfo().setWork_state(itemModel.getVal());
                break;
            case YSConstant.POP_TYPE_COLOR:
                car_color_tv.setText(itemModel.getText());
                CarDataManager.getInstance().getmCarAddInfo().setColor(itemModel.getVal());
                break;
            case YSConstant.POP_TYPE_DECORATE:
                car_decorate_tv.setText(itemModel.getText());
                CarDataManager.getInstance().getmCarAddInfo().setInterior(itemModel.getVal());
                break;
            case YSConstant.POP_TYPE_APPERANCE:
                car_apperance_tv.setText(itemModel.getText());
                CarDataManager.getInstance().getmCarAddInfo().setSurface(itemModel.getVal());
                break;
        }
    }

    @Override
    public void onFail(String msg) {
        ToastUtils.showToast(msg);
    }
}
